import { DatePickerView, PickerView, Popup, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { Navigate, useNavigate } from 'react-router-dom'
import http from '../../api'
import Loading from '../../components/publicComponents/Loading'
import PubNav from '../../components/publicComponents/pubNav'
import { UserInfoResult } from '../../myTypes'
import style from './userInfo.module.css'

const columns = [['男', '女']]

export default function UserInfo() {
  const navigate = useNavigate()
  let [userId, setUserId] = useState('')
  const [visible, setVisible] = useState(false)
  const [visible1, setVisible1] = useState(false)
  const [sex, setSex] = useState<(string | null)[]>(['男'])
  const [birthday, setBirthday] = useState(new Date('1998-01-01'))
  const [nickname, setNickname] = useState('')
  const [desc, setDesc] = useState('')
  const [head, setHead] = useState('')

  useEffect(() => {
    const id = localStorage.getItem('userId')
    if (id) {
      userId = id
      setUserId(id)
      sendRequestUserInfo()
    } else {
      navigate('/login')
    }
  }, [])

  async function sendRequestUserInfo() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await http('get', '/mty/my/info', {
      accountId: userId
    })
    Toast.clear()
    if (data) {
      const userInfo = data.data as UserInfoResult
      setHead(userInfo.headImg)
      setSex([userInfo.sex ? userInfo.sex : '男'])
      setBirthday(new Date(userInfo.birthday))
      setNickname(userInfo.nickName)
      setDesc(userInfo.signature)
    }
  }

  function formatDate(date: Date) {
    let d = date.toLocaleDateString().split('/')
    d[1] = parseInt(d[1]) < 10 ? '0' + d[1] : d[1]
    d[2] = parseInt(d[2]) < 10 ? '0' + d[2] : d[2]
    return d.join('-')
  }
  async function updateUserInfo() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await http('post', '/mty/my/update', {
      id: userId,
      nickName: nickname,
      headImg: head,
      sex: sex[0],
      birthday: formatDate(birthday),
      signature: desc
    })
    Toast.clear()
    if (data && data.code === 200) {
      Toast.show({
        content: '修改成功',
        duration: 2000
      })
    }
  }

  return (
    <div style={{ paddingTop: '46px' }}>
      <PubNav title="修改个人资料" />
      {/* 用户头像 */}
      <div className={style['head']}>
        <div className={style['head-icon']}>
          <img src={head} alt="" />
          <div className={style['update-icon']}>
            <img src="/static/use/icon-edit-ebe.png" alt="" />
          </div>
        </div>
      </div>
      {/* 用户信息 */}
      <div className={style['user-info']}>
        {/* 用户昵称 */}
        <div className={style['nickname']}>
          <div className={style['title']}>昵称:</div>
          <div className={style['nickname-ipt']}>
            <input
              type="text"
              value={nickname}
              onChange={(e) => {
                setNickname(e.target.value)
              }}
            />
          </div>
        </div>
        {/* 性别 */}
        <div
          className={style['gender']}
          onClick={() => {
            setVisible(true)
          }}
        >
          <div className={style['title']}>性别:</div>
          <div className={style['gender-ipt']}>{sex}</div>
        </div>
        {/* 生日 */}
        <div className={style['birthday']}>
          <div className={style['title']}>生日:</div>
          <div
            className={style['birthday-ipt']}
            onClick={() => {
              setVisible1(true)
            }}
          >
            {formatDate(birthday)}
          </div>
        </div>
        {/* 个性宣言 */}
        <div className={style['user-desc']}>
          <div className={style['title']}>个性宣言:</div>
          <div className={style['desc-icon']}>
            <textarea
              value={desc}
              cols={30}
              rows={2}
              maxLength={60}
              onChange={(e) => {
                setDesc(e.target.value)
              }}
            ></textarea>
          </div>
        </div>
      </div>

      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false)
        }}
      >
        <PickerView
          columns={columns}
          value={sex}
          onChange={(val) => {
            setSex(val)
          }}
        />
        <div
          className={style['sex-body']}
          onClick={() => {
            setVisible(false)
          }}
        >
          确定
        </div>
      </Popup>

      <Popup
        visible={visible1}
        onMaskClick={() => {
          setVisible1(false)
        }}
      >
        <DatePickerView
          min={new Date('1960-01-01')}
          max={new Date()}
          value={birthday}
          onChange={(val) => {
            setBirthday(val)
          }}
        />
        <div
          className={style['sex-body']}
          onClick={() => {
            setVisible(false)
          }}
        >
          确定
        </div>
      </Popup>

      <div className={style['submit']} onClick={updateUserInfo}>
        完成
      </div>
    </div>
  )
}
